package com.chenbei.common.handler.serializer;

import cn.hutool.core.util.StrUtil;
import com.chenbei.common.enums.DesensitizeTypeEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Objects;

public class DesensitizeSerializer extends JsonSerializer<Object> {

    private final DesensitizeTypeEnum type;

    public DesensitizeSerializer(DesensitizeTypeEnum type) {
        this.type = type;
    }

    @Override
    public void serialize(Object s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (s instanceof String) {
            String formatStr = (String) s;
            if (Objects.equals(type.getType(), DesensitizeTypeEnum.PHONE.getType())) {
                if (StrUtil.isNotBlank(formatStr)) {
                    if (formatStr.length() <= 7) {
                        formatStr = "*******";
                    } else {
                        String head = formatStr.substring(0, 3); // 前三个字符
                        String tail = formatStr.substring(formatStr.length() - 4); // 后四个字符

                        StringBuilder middle = new StringBuilder();
                        for (int i = 0; i < formatStr.length() - 7; i++) {
                            middle.append('*');
                        }

                        formatStr = head + middle + tail;
                    }
                }
            }
            jsonGenerator.writeString(formatStr);
        } else {
            serializerProvider.defaultSerializeValue(s, jsonGenerator);
        }
    }
}
